package com.cxs.handler.impl;

import com.cxs.handler.ResultHandler;
import com.cxs.utils.UnderlineToHumpCaseUtil;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project: jdbc
 * @Author: cxs2014501@163.com
 * @Create: 2022/8/31 15:34
 * @Description:
 **/
public class ResultBeanAsBeanHandler<T> implements ResultHandler<T> {

    private Class<T> tClass;

    public ResultBeanAsBeanHandler(Class tClass){
        this.tClass = tClass;
    }
    @Override
    public T resultHandle(ResultSet resultSet) {
        T result = null;
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            if (resultSet.next()) {
                T obj = this.tClass.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    try {
                        String name = metaData.getColumnLabel(i);
                        PropertyDescriptor pd = new PropertyDescriptor(UnderlineToHumpCaseUtil.underlineToHumpCase(name), tClass);
                        pd.getWriteMethod().invoke(obj, resultSet.getObject(name));
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
                result = obj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
